<template>
  <h2 style="text-align: center">餐具消毒记录表</h2>
  <el-form :model="form">
    <el-form-item prop="cleanDate" label="日期" :label-width="labelWidth">
      <el-date-picker
        v-model="form.cleanDate"
        type="date"
        value-format="YYYY-MM-DD"
      />
    </el-form-item>
    <el-form-item prop="mealTimes" label="餐次" :label-width="labelWidth">
      <SingleLayerSelect
        :options="[
          { label: '早餐', value: '早餐' },
          { label: '午餐', value: '午餐' },
          { label: '晚餐', value: '晚餐' },
        ]"
        v-model="form.mealTimes"
      />
    </el-form-item>
    <el-form-item prop="recorder" label="记录人" :label-width="labelWidth">
      <el-input v-model="form.recorder"></el-input>
    </el-form-item>
    <el-form-item prop="type" label="消毒方式" :label-width="labelWidth">
      <el-checkbox-group
        v-model="form.type"
        @update:model-value="handleSelectChange"
      >
        <template v-for="item of disinfectionTypeList">
          <el-divider content-position="left">{{ item.mainType }}</el-divider>
          <el-checkbox
            v-for="subType of item.subTypeList"
            :label="subType.name"
            :value="subType.id"
            style="width: 230px"
          />
        </template>
      </el-checkbox-group>
    </el-form-item>
    <el-table :span-method="objectSpanMethod" :data="tableData" border>
      <el-table-column
        :width="item.width ?? '150px'"
        v-for="item of items"
        :prop="item.field"
        :label="item.label"
        :fixed="item.fixed ?? false"
        align="center"
      >
        <template #default="{ row, column, $index }">
          <template v-if="item.field === 'disinfectionMethod'">
            <template v-if="row[item.field].configList.length > 0">
              <el-row>
                <el-col :span="8" style="text-align: right">
                  {{ row[item.field].name }}
                </el-col>
                <el-col :span="8" v-for="config of row[item.field].configList">
                  <el-row :gutter="4">
                    <el-col :span="8">
                      <span>{{ config.name }}:</span>
                    </el-col>
                    <el-col :span="16">
                      <template v-if="config.type === 'input'">
                        <el-input
                          v-model="
                            form[`${row[item.field].name}**${config.name}`]
                          "
                        >
                          <template
                            #prepend
                            v-if="config.value.split('（  ）')[0]"
                            >{{ config.value.split("（  ）")[0] }}</template
                          >
                          <template
                            #append
                            v-if="config.value.split('（  ）').reverse()[0]"
                            >{{
                              config.value.split("（  ）").reverse()[0]
                            }}</template
                          >
                        </el-input>
                      </template>
                      <template v-else-if="config.type === 'select'">
                        <SingleLayerSelect
                          :options="
                            JSON.parse(config.config).options.map((x) => ({
                              label: x,
                              value: x,
                            }))
                          "
                          v-model="
                            form[`${row[item.field].name}**${config.name}`]
                          "
                        />
                      </template>
                    </el-col>
                  </el-row>
                </el-col>
                <!-- <SingleLayerSelect v-else-if="config.type === 'select'" :options="JSON.parse(config.config).options"/> -->
              </el-row>
            </template>
            <template v-else>
              {{ row[item.field].name }}
            </template>
            <!-- <template v-else>
                {{ row[item.field].configList }}
            </template> -->
          </template>
          <template v-else>
            <el-input
              v-model="form[`${item.field}-${row['disinfectionMethod'].name}`]"
              v-if="item.type === 'input'"
            ></el-input>
            <template v-else>{{ row[item.field] }}</template>
          </template>
        </template>
      </el-table-column>
    </el-table>
  </el-form>
  <el-row justify="end" style="margin-top: 20px">
    <el-button type="primary" @click="handleSave">确认</el-button>
    <el-button plain @click="$emit('callBack')">关闭</el-button>
  </el-row>
</template>

<script setup lang="ts">
import AssistCleanInfoApi from "~/src/api/webPath/AssistCleanInfoApi";
import SysDataApi from "~/src/api/webPath/sysDataApi";
import SysDataParamApi from "~/src/api/webPath/sysDataParamApi";
import { useUserName } from "~/src/utils/useUserName";

const props = defineProps<{
  modelValue: {
    query: any;
  };
}>();
const emit = defineEmits(["callBack"])

const form = ref({
  cleanDate: "",
  mealTimes: "",
  recorder: "",
  type: [],
});
const tableData = ref<any[]>([]);
const labelWidth = "80px";
const items = [
  {
    field: "cleanDate",
    label: "消毒日期",
  },
  {
    field: "mealTimes",
    label: "消毒餐次",
    width: "80px"
  },
  {
    field: "disinfectionType",
    label: "消毒方式",
    fixed: "left",
    width: "110px"
  },
  {
    field: "disinfectionMethod",
    label: "消毒方式及时间",
    width: "800px",
  },
  {
    field: "stainlessPlateNum",
    label: "不锈钢快餐盘",
    type: "input",
    width: "120px"
  },
  {
    field: "stainlessBowlNum",
    label: "不锈钢汤碗",
    type: "input",
    width: "120px"
  },
  {
    field: "chopsticksNum",
    label: "筷子",
    type: "input",
    width: "80px"
  },
  {
    field: "spoonNum",
    label: "汤匙",
    type: "input",
    width: "80px"
  },
  {
    field: "stainlessBucketNum",
    label: "不锈钢桶/罐",
    type: "input",
    width: "120px"
  },
  {
    field: "stainlessBasinNum",
    label: "不锈钢大盆",
    type: "input",
    width: "120px"
  },
  {
    field: "melamineTablewareNum",
    label: "密胺餐具",
    type: "input",
    width: "120px"
  },
  {
    field: "knifeBoardNum",
    label: "刀、砧板",
    type: "input",
    width: "120px"
  },
  {
    field: "shovelSpoonNum",
    label: "铲、菜勺",
    type: "input",
    width: "120px"
  },
  {
    field: "ragNum",
    label: "抹布",
    type: "input",
    width: "80px"
  },
  {
    field: "plasticBasketNum",
    label: "塑料筐",
    type: "input",
    width: "80px"
  },
  {
    field: "turnoverBoxNum",
    label: "周转箱",
    type: "input",
    width: "80px"
  },
  {
    field: "lunchBoxCoverNum",
    label: "餐盒盖",
    type: "input",
    width: "80px"
  },
];
const mainTypeList = ref<string[]>([]);

const disinfectionTypeList = ref([]);
const targetObjList = ref<any[]>([]);
enum ParamType {
  text = "text",
  select = "select",
  input = "input",
}

const userName = useUserName()
onBeforeMount(async () => {
  const res = await SysDataApi.getPageData({ type: "disinfection_type" });

  if (res) {
    const { data } = res;
    Promise.all(
      data.map(async (x) => {
        const obj = {
          mainType: x.name,
        };

        const detailRes = await SysDataApi.getPageData({
          type: "disinfection_type",
          pid: x.id,
        });
        if (detailRes) {
          const { data: detailData } = detailRes;

          obj.subTypeList = await Promise.all(
            detailData.map(async (y) => {
              const paramRes = await SysDataParamApi.getPageData({
                sysDataId: y.id,
              });
              const paramData = paramRes && paramRes.data;
              let obj = {};
              obj.name = `${y.name}`;
              obj.configList = [];
              paramData.forEach((z) => {
                if (z.type === ParamType.text) {
                    obj.name += `-${z.name} ${z.value}`;
                } else {
                  obj.configList.push({
                    type: z.type,
                    name: z.name,
                    value: z.value,
                    config: z.config,
                  });
                }
              });
              return {
                id: y.id,
                sort: y.sort,
                ...obj,
              };
            })
          );
        }
        disinfectionTypeList.value.push(obj);
      })
    ).then((v) => {
      console.log("disinfectionTypeList ", disinfectionTypeList.value);

      // 编辑页面
      if (props.modelValue.query.assistCleanInfoId) {
        AssistCleanInfoApi.getDetail({
          assistCleanInfoId: props.modelValue.query.assistCleanInfoId,
        }).then((res) => {
          console.log("getDetail", res);
          if (res) {
            const { data: {list: data} }  = res
            console.log("detail data",data)
            
            
            targetObjList.value = []
            const firstItem = data.length > 0 && data[0]
            for (const key of ["cleanDate","mealTimes","recorder"]) {
                form.value[key] = firstItem[key]
            }

            // 编辑返回数据列表
            data.forEach(item=>{
                const { disinfectionMethod, ...rest } = item 
                console.log("rest",rest)
                const x = disinfectionTypeList.value.find(x=>x.mainType === rest.disinfectionType)
                const y = x.subTypeList.find(subType=>disinfectionMethod.includes(subType.name))

                const objItem = targetObjList.value.find((z) => z.mainType === x.mainType);
                if (objItem) {
                    objItem.children.push(y);
                } else {
                    targetObjList.value.push({
                        mainType: x.mainType,
                        children: [y],
                    });
                }
                console.log("current x",x,"current y",y,"objItem",objItem)
                
                    // if (y.configList.length > 0){
                    //     y.configList.forEach(z=>{
                    //         console.log("z config",z.config)
                    //         if (z.config !== "" && z.config !== null) {
                    //             const config = JSON.parse(z.config)
                    //             const optionList = config.options

                    //             if (optionList) {
                    //                 console.log("current optionsList",optionList)
                    //                 form.value[`${y.name}**${z.name}`] = optionList[0]
                    //             } else if (config.default) {
                    //                 form.value[`${y.name}**${z.name}`] = config.default
                    //             }
                    //         }
                    //     })
                    // }

                console.log("edit y",y,"main type",x.mainType)
                const row = {
                    cleanDate: rest.cleanDate,
                    mealTimes: rest.mealTimes,
                    disinfectionType: rest.disinfectionType,
                    disinfectionMethod: y,
                    stainlessPlateNum: rest.stainlessPlateNum,
                    stainlessBowlNum: rest.stainlessBowlNum,
                    chopsticksNum: rest.chopsticksNum,
                    spoonNum: rest.spoonNum,
                    stainlessBucketNum: rest.stainlessBucketNum,
                    stainlessBasinNum: rest.stainlessBasinNum,
                    melamineTablewareNum: rest.melamineTablewareNum,
                    knifeBoardNum: rest.knifeBoardNum,
                    shovelSpoonNum: rest.shovelSpoonNum,
                    ragNum: rest.ragNum,
                    plasticBasketNum: rest.plasticBasketNum,
                    turnoverBoxNum: rest.turnoverBoxNum,
                    lunchBoxCoverNum: rest.lunchBoxCoverNum,
                }

                tableData.value.push(row);

                tableData.value.sort((a,b)=>{
                    return a.disinfectionMethod.sort - b.disinfectionMethod.sort
                })
                console.log("tableData...",tableData.value)
                // 数量输入项赋值
                for (const key of Object.keys(rest)) {
                    form.value[`${key}-${y.name}`] = rest[key]
                }

                const paramList = disinfectionMethod.split(y.name)
                if (paramList.length > 1){
                    const paramStr = paramList[1]
                    y.configList.forEach(config=>{
                        let value = paramStr.split(`${config.name}: `)[1].trim()
                        if (value.includes(" ")) {
                           value = value.split(" ")[0]
                        }
                        form.value[`${y.name}**${config.name}`] = value
                    })
                }
                
            })

            console.log("tabledata value",tableData.value)
            form.value.type = tableData.value.map(x=>x.disinfectionMethod.id)

            mainTypeList.value = form.value.type.map(x=>{
              const obj = disinfectionTypeList.value.find((y)=>y.subTypeList.some(z=>z.id === x))
              const targetSubType = obj.subTypeList.find(y=>y.id === x)
              return {
                  type: obj.mainType,
                  ...targetSubType
              }
            })
            console.log("form.value",form.value)
          }
        });
      } else {

        const date = new Date()
        // 默认当天
        form.value.cleanDate = `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2,"0")}-${date.getDate().toString().padStart(2,"0")}`  
        // 默认给当前登录用户名
        form.value.recorder = userName
        // 新增页面，赋予配置项初始默认值
        disinfectionTypeList.value.forEach(x=>{
            x.subTypeList.forEach(y=>{
                y.configList.forEach(z=>{
                    console.log("z config",z.config)
                    if (z.config !== "" && z.config !== null) {
                        const config = JSON.parse(z.config)
                        const optionList = config.options

                        if (optionList) {
                            console.log("current optionsList",optionList)
                            form.value[`${y.name}**${z.name}`] = optionList[0]
                        } else if (config.default) {
                            form.value[`${y.name}**${z.name}`] = config.default
                        }
                    }
                })
            })
        })

        initTable();
      }

    });
  }
});
function initTable() {
  targetObjList.value = [];
  mainTypeList.value.forEach((y) => {
    console.log("yyyy type",y,"targetObjList",targetObjList.value)
    const objItem = targetObjList.value.find((z) => z.mainType === y.type);
    console.log("current objItem",objItem)
    if (objItem) {
      objItem.children.push(y);
    } else {
      targetObjList.value.push({
        mainType: y.type,
        children: [y],
      });
    }
  });

  console.log("current obj", targetObjList.value);

  targetObjList.value.sort((a,b)=>{
    return a.children[0].sort - b.children[0].sort
  })
  tableData.value = [];
  targetObjList.value.forEach((x) => {
    x.children
      .sort((a, b) => a.sort - b.sort)
      .forEach((y) => {
        tableData.value.push({
          cleanDate: form.value.cleanDate,
          mealTimes: form.value.mealTimes,
          disinfectionType: x.mainType,
          disinfectionMethod: y,
          stainlessPlateNum: "",
          stainlessBowlNum: "",
          chopsticksNum: "",
          spoonNum: "",
          stainlessBucketNum: "",
          stainlessBasinNum: "",
          melamineTablewareNum: "",
          knifeBoardNum: "",
          shovelSpoonNum: "",
          ragNum: "",
          plasticBasketNum: "",
          turnoverBoxNum: "",
          lunchBoxCoverNum: "",
        });
      });
  });
}


const objectSpanMethod = ({ row, column, rowIndex, columnIndex }) => {
  if (columnIndex < 3) {
    console.log("targetObjList",targetObjList.value,"disinfectionType",row.disinfectionType)
    targetObjList.value.sort((a,b)=>a.children[0].sort - b.children[0].sort)
    const targetObj = targetObjList.value.find(
      (x) => x.mainType === row.disinfectionType
    );
    const index = targetObjList.value.indexOf(targetObj);
    console.log("rowIndex",rowIndex)
    console.log("span index",index)
    if (
      rowIndex ===
      index * targetObjList.value[index - 1 < 0 ? 0 : index - 1].children.length
    ) {
      return {
        rowspan: targetObj.children.length,
        colspan: 1,
      };
    } else {
      return {
        rowspan: 0,
        colspan: 0,
      };
    }
  }
};
function handleSave() {
  const finalData = [];
  mainTypeList.value.sort((a, b) => {
    return a.sort - b.sort;
  });
  const finalTypeList = mainTypeList.value.map(x=>x.name)
  for (const key of Object.keys(form.value)) {
    const [itemKey, ...index] = key.split("-");
    const concatIndex = index.join("-")
    if ((key.includes("Num")  || (key.includes("id") && props.modelValue.query.assistCleanInfoId)) && finalTypeList.includes(concatIndex)) {
      console.log("curren key",key,"index",concatIndex, finalTypeList)
      const data = finalData.find((x) => x.index == concatIndex);
      if (data) {
        data[itemKey] = form.value[key];
      } else {
        finalData.push({ index:concatIndex, [itemKey]: form.value[key] });
      }
    }
  }
  finalData.forEach((x) => {
    console.log("kkkk", x, tableData.value);
    const row = tableData.value.find(b=>b.disinfectionMethod.name === x.index);
    console.log("row", row);
    for (const key of Object.keys(row)) {
      console.log("key",key)
      if (!key.includes("Num")) {
        // 消毒方式和时间特殊处理
        if (key === "disinfectionMethod") {
          const { name, configList } = row[key];
          let finalName = name + " ";
          console.log("name:", name, "configList", configList);
          configList.forEach((config) => {
            const configValue = form.value[`${name}**${config.name}`];

            if (config.type === "input") {
              const prependText = config.value.split("（  ）")[0];
              const appendText = config.value.split("（  ）").reverse()[0];
              finalName += `${config.name}: ${prependText} ${configValue} ${appendText} `;
            } else {
              finalName += `${config.name}: ${configValue} `;
            }
            console.log(
              "config :",
              `${name}**${config.name}`,
              " value",
              configValue
            );
          });
          x[key] = finalName;
        } else if (key === "cleanDate") {
          x[key] = `${row[key]} 00:00:00`;
        } else {
            console.log("finalData key",key)
          x[key] = row[key];
        }

        x.recorder = form.value.recorder
      }
    }
  });

  finalData.forEach((x) => {
    delete x.index;
  });
  console.log("finalData", finalData);
  const obj = { list: finalData }
  if (props.modelValue.query.assistCleanInfoId) {
    obj.id = props.modelValue.query.assistCleanInfoId
  } 
  AssistCleanInfoApi.save(obj).then((res) => {
    console.log("res", res);
    if (res){
       const { message } = res
       $baseMessage(message,"success")
    }
    emit("callBack")
  });
}


function handleSelectChange(v: any) {
  const allSubTypeList = []
  disinfectionTypeList.value.find(x=>{
      allSubTypeList.push(...x.subTypeList)
  })
  mainTypeList.value = v.map(x=>{
    const obj = disinfectionTypeList.value.find((y)=>y.subTypeList.some(z=>z.id === x))
    const targetSubType = obj.subTypeList.find(y=>y.id === x)
    return {
        type: obj.mainType,
        ...targetSubType
    }
  })
  console.log("mainTypeList",mainTypeList.value)
  initTable();
}
</script>

<style scoped></style>
